package cn.daniellee.plugin.otp.menu;

import cn.daniellee.plugin.otp.OptimizedTeleport;
import cn.daniellee.plugin.otp.component.ItemGenerator;
import cn.daniellee.plugin.otp.menu.holder.PlayerMenuHolder;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;

import java.util.List;
import java.util.stream.Collectors;

public class PlayerMenu {

	public static Inventory generate(String oneself, int page) {
		List<Player> players = Bukkit.getOnlinePlayers().stream().filter(item -> !oneself.equals(item.getName())).collect(Collectors.toList());
		int size = players.size() > 45 ? 54 : 45;
		Inventory menu = Bukkit.createInventory(new PlayerMenuHolder(), size, OptimizedTeleport.getInstance().getConfig().getString("menu.title", "&eSelect target").replace("&", "§"));

		List<String> playerLore = OptimizedTeleport.getInstance().getConfig().getStringList("menu.button.lore");
		for (int i = 0; i < 45; i++) {
			int targetIndex = i + 45 * (page - 1);
			if (targetIndex >= players.size()) break;
			Player player = players.get(targetIndex);
			menu.setItem(i, ItemGenerator.getSkullItem(player.getName(), "&a" + player.getName(), playerLore));
		}

		if (size == 54) {
			// 上一页按钮
			if (page > 1) {
				menu.setItem(45, ItemGenerator.getItem(OptimizedTeleport.getInstance().getConfig().getString("menu.button.back.name", "&eBack to {page}").replace("{page}", "[" + (page - 1) + "]"), null, OptimizedTeleport.getInstance().getConfig().getString("menu.button.back.item.material", "RED_WOOL"), OptimizedTeleport.getInstance().getConfig().getInt("menu.button.back.item.durability", 0)));
			}
			// 下一页按钮
			if (45 * page < players.size()) {
				menu.setItem(53, ItemGenerator.getItem(OptimizedTeleport.getInstance().getConfig().getString("menu.button.next.name", "&eNext to {page}").replace("{page}", "[" + (page + 1) + "]"), null, OptimizedTeleport.getInstance().getConfig().getString("menu.button.next.item.material", "LIME_WOOL"), OptimizedTeleport.getInstance().getConfig().getInt("menu.button.next.item.durability", 0)));
			}
		}
		return menu;
	}

}
